using AutoMapper;
using B.S.BaseData.Api.Write.Applicantion.Command.OrderCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure;
using MediatR;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.EntityFrameworkCore;
using WorkOrder.Domain;

namespace B.S.BaseData.Api.Write.Applicantion.CommandHandler.OrderCommandHandler
{
    /// <summary>
    /// 删除处方流转订单处理器（软删除）
    /// </summary>
    public class DeletePrescriptionOrderHandler : IRequestHandler<DeletePrescriptionOrderCommand, APIResult<bool>>
    {
        private readonly BaseDbContext _context;
        private readonly IMapper _mapper;

        public DeletePrescriptionOrderHandler(BaseDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public async Task<APIResult<bool>> Handle(DeletePrescriptionOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var order = await _context.PrescriptionOrders
                    .FirstOrDefaultAsync(p => p.OrderNumber == request.OrderNumber && !p.IsDelete, cancellationToken);

                if (order == null)
                {
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到指定的处方流转订单或该订单已被删除",
                        Data = false
                    };
                }

                // 检查订单状态，只有已失效的订单才能删除
                if (order.OrderStatus != "已失效")
                {
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "只有已失效的处方流转订单才能删除",
                        Data = false
                    };
                }

                // 执行软删除
                order.IsDelete = true;
                order.UpdateTime = DateTime.Now;

                _context.PrescriptionOrders.Update(order);
                await _context.SaveChangesAsync(cancellationToken);

                return new APIResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = "删除成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = $"删除失败: {ex.Message}",
                    Data = false
                };
            }
        }
    }

    /// <summary>
    /// 批量删除处方流转订单处理器（软删除）
    /// </summary>
    public class BatchDeletePrescriptionOrderHandler : IRequestHandler<BatchDeletePrescriptionOrderCommand, APIResult<bool>>
    {
        private readonly BaseDbContext _context;
        private readonly IMapper _mapper;

        public BatchDeletePrescriptionOrderHandler(BaseDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public async Task<APIResult<bool>> Handle(BatchDeletePrescriptionOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (request.OrderNumbers == null || !request.OrderNumbers.Any())
                {
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "请选择要删除的处方流转订单",
                        Data = false
                    };
                }

                var orders = await _context.PrescriptionOrders
                    .Where(p => request.OrderNumbers.Contains(p.OrderNumber) && !p.IsDelete)
                    .ToListAsync(cancellationToken);

                if (!orders.Any())
                {
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到指定的处方流转订单或订单已被删除",
                        Data = false
                    };
                }

                // 检查是否有非已失效状态的订单
                var nonInvalidOrders = orders.Where(o => o.OrderStatus != "已失效").ToList();
                if (nonInvalidOrders.Any())
                {
                    var nonInvalidOrderNumbers = string.Join(", ", nonInvalidOrders.Select(o => o.OrderNumber));
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = $"以下非已失效状态的处方流转订单不能删除: {nonInvalidOrderNumbers}",
                        Data = false
                    };
                }

                // 执行批量软删除
                foreach (var order in orders)
                {
                    order.IsDelete = true;
                    order.UpdateTime = DateTime.Now;
                }

                _context.PrescriptionOrders.UpdateRange(orders);
                await _context.SaveChangesAsync(cancellationToken);

                return new APIResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = $"成功删除 {orders.Count} 个处方流转订单",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = $"批量删除失败: {ex.Message}",
                    Data = false
                };
            }
        }
    }

    /// <summary>
    /// 核准发药处理器
    /// </summary>
    public class ApproveDispensingHandler : IRequestHandler<ApproveDispensingCommand, APIResult<bool>>
    {
        private readonly BaseDbContext _context;
        private readonly IMapper _mapper;

        public ApproveDispensingHandler(BaseDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public async Task<APIResult<bool>> Handle(ApproveDispensingCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var order = await _context.PrescriptionOrders
                    .FirstOrDefaultAsync(p => p.OrderNumber == request.OrderNumber && !p.IsDelete, cancellationToken);

                if (order == null)
                {
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到指定的处方流转订单或该订单已被删除",
                        Data = false
                    };
                }

                // 检查发药状态，只有未核准发药的订单才能核准
                if (order.DispenseStatus != "核准发药")
                {
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "只有未核准发药的处方流转订单才能核准发药",
                        Data = false
                    };
                }

                // 更新发药状态
                order.DispenseStatus = "已核准发药";
                order.UpdateTime = DateTime.Now;

                _context.PrescriptionOrders.Update(order);
                await _context.SaveChangesAsync(cancellationToken);

                return new APIResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = "核准发药成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = $"核准发药失败: {ex.Message}",
                    Data = false
                };
            }
        }
    }

    /// <summary>
    /// 更新处方流转订单处理器
    /// </summary>
    public class UpdatePrescriptionOrderHandler : IRequestHandler<UpdatePrescriptionOrderCommand, APIResult<bool>>
    {
        private readonly BaseDbContext _context;
        private readonly IMapper _mapper;

        public UpdatePrescriptionOrderHandler(BaseDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public async Task<APIResult<bool>> Handle(UpdatePrescriptionOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var order = await _context.PrescriptionOrders
                    .FirstOrDefaultAsync(p => p.OrderNumber == request.OrderNumber && !p.IsDelete, cancellationToken);

                if (order == null)
                {
                    return new APIResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到指定的处方流转订单或该订单已被删除",
                        Data = false
                    };
                }

                // 更新患者信息
                if (!string.IsNullOrEmpty(request.PatientName))
                    order.PatientName = request.PatientName;

                if (!string.IsNullOrEmpty(request.PatientGender))
                    order.PatientGender = request.PatientGender;

                if (request.PatientAge.HasValue)
                    order.PatientAge = request.PatientAge.Value;

                if (!string.IsNullOrEmpty(request.PatientPhone))
                    order.PatientPhone = request.PatientPhone;

                if (!string.IsNullOrEmpty(request.Disease))
                    order.Disease = request.Disease;

                if (!string.IsNullOrEmpty(request.LiverFunction))
                    order.LiverFunction = request.LiverFunction;

                if (!string.IsNullOrEmpty(request.KidneyFunction))
                    order.KidneyFunction = request.KidneyFunction;

                if (!string.IsNullOrEmpty(request.AllergyHistory))
                    order.AllergyHistory = request.AllergyHistory;

                if (!string.IsNullOrEmpty(request.PregnancyStatus))
                    order.PregnancyStatus = request.PregnancyStatus;

                if (!string.IsNullOrEmpty(request.SymptomDescription))
                    order.SymptomDescription = request.SymptomDescription;

                // 更新处方信息
                if (!string.IsNullOrEmpty(request.DoctorName))
                    order.DoctorName = request.DoctorName;

                if (!string.IsNullOrEmpty(request.Department))
                    order.Department = request.Department;

                if (!string.IsNullOrEmpty(request.PreliminaryDiagnosis))
                    order.PreliminaryDiagnosis = request.PreliminaryDiagnosis;

                if (!string.IsNullOrEmpty(request.TreatmentAdvice))
                    order.TreatmentAdvice = request.TreatmentAdvice;

                // 更新订单信息
                if (!string.IsNullOrEmpty(request.OrderStatus))
                    order.OrderStatus = request.OrderStatus;

                if (request.TotalAmount.HasValue)
                    order.TotalAmount = request.TotalAmount.Value;

                if (request.CouponAmount.HasValue)
                    order.CouponAmount = request.CouponAmount.Value;

                // 重新计算实际支付金额
                if (request.TotalAmount.HasValue || request.CouponAmount.HasValue)
                {
                    var totalAmount = request.TotalAmount ?? order.TotalAmount;
                    var couponAmount = request.CouponAmount ?? order.CouponAmount ?? 0;
                    order.ActualPayment = totalAmount - couponAmount;
                }

                order.UpdateTime = DateTime.Now;

                _context.PrescriptionOrders.Update(order);
                await _context.SaveChangesAsync(cancellationToken);

                return new APIResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = "更新成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = $"更新失败: {ex.Message}",
                    Data = false
                };
            }
        }
    }
}

/// <summary>
/// 药品订单发货处理程序
/// </summary>
public class ShipMedicineOrderHandler : IRequestHandler<ShipMedicineOrderCommand, APIResult<bool>>
{
    private readonly BaseDbContext _dbContext;

    public ShipMedicineOrderHandler(BaseDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<APIResult<bool>> Handle(ShipMedicineOrderCommand request, CancellationToken cancellationToken)
    {
        try
        {
            // 查找药品订单
            var medicineOrder = await _dbContext.Set<MedicineOrder>()
                .FirstOrDefaultAsync(o => o.OrderNumber == request.OrderNumber, cancellationToken);
            
            if (medicineOrder == null)
            {
                return new APIResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = "药品订单不存在",
                    Data = false
                };
            }

            // 检查订单状态是否为待发货
            if (medicineOrder.OrderStatus != "待发货")
            {
                return new APIResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = "订单状态不正确，只有待发货状态的订单才能发货",
                    Data = false
                };
            }

            // 更新订单信息
            medicineOrder.LogisticsCompany = request.LogisticsCompany;
            medicineOrder.TrackingNumber = request.TrackingNumber;
            medicineOrder.OrderStatus = "待收货";
            medicineOrder.UpdateTime = DateTime.Now;

            // 保存到数据库
            _dbContext.Set<MedicineOrder>().Update(medicineOrder);
            await _dbContext.SaveChangesAsync(cancellationToken);

            return new APIResult<bool>
            {
                Code = ApiEnum.Success,
                Msg = "发货成功",
                Data = true
            };
        }
        catch (Exception ex)
        {
            return new APIResult<bool>
            {
                Code = ApiEnum.Fail,
                Msg = $"发货失败: {ex.Message}",
                Data = false
            };
        }
    }
} 

/// <summary>
/// 确认收货处理程序
/// </summary>
public class ConfirmReceiptHandler : IRequestHandler<ConfirmReceiptCommand, APIResult<bool>>
{
    private readonly BaseDbContext _dbContext;

    public ConfirmReceiptHandler(BaseDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<APIResult<bool>> Handle(ConfirmReceiptCommand request, CancellationToken cancellationToken)
    {
        try
        {
            // 查找药品订单
            var medicineOrder = await _dbContext.Set<MedicineOrder>()
                .FirstOrDefaultAsync(o => o.OrderNumber == request.OrderNumber, cancellationToken);
            
            if (medicineOrder == null)
            {
                return new APIResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = "药品订单不存在",
                    Data = false
                };
            }

            // 检查订单状态是否为待收货
            if (medicineOrder.OrderStatus != "待收货")
            {
                return new APIResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = "订单状态不正确，只有待收货状态的订单才能确认收货",
                    Data = false
                };
            }

            // 更新订单状态为已收货
            medicineOrder.OrderStatus = "已收货";
            medicineOrder.UpdateTime = DateTime.Now;

            // 保存到数据库
            _dbContext.Set<MedicineOrder>().Update(medicineOrder);
            await _dbContext.SaveChangesAsync(cancellationToken);

            return new APIResult<bool>
            {
                Code = ApiEnum.Success,
                Msg = "确认收货成功",
                Data = true
            };
        }
        catch (Exception ex)
        {
            return new APIResult<bool>
            {
                Code = ApiEnum.Fail,
                Msg = $"确认收货失败: {ex.Message}",
                Data = false
            };
        }
    }
} 